#include "MysqlConnAutoPtr.h"

#define LOGGER_NAME "shadow.mysql.mysqlconnautoptr"

MysqlConnAutoPtr::MysqlConnAutoPtr(MysqlConnPool * pool) {
		_logger = log4cxx::Logger::getLogger(LOGGER_NAME);
		_pool = NULL;
		_mysql_conn = NULL;
		if (NULL == pool) {
				LOG4CXX_ERROR(_logger, "MysqlConnAutoPtr constructor error, pool is null");
				return;
		}
		_pool = pool;
}

MYSQL_CONN * MysqlConnAutoPtr::acquire() {
		if (_mysql_conn != NULL) return _mysql_conn;
		if (NULL == _pool) {
				LOG4CXX_ERROR(_logger, "try to acquire mysql conn from mysql conn pool which is empty");
				return NULL;
		}
		_mysql_conn = _pool->acquire_conn();
		return _mysql_conn;
}

int MysqlConnAutoPtr::release() {
		if (NULL == _pool || NULL == _mysql_conn) {
				LOG4CXX_WARN(_logger, "try to release a mysql conn to pool which might be empty");
				return -1;
		}
		_pool->release_conn(_mysql_conn);
		_mysql_conn = NULL;
		return 1;
}

MysqlConnAutoPtr::~MysqlConnAutoPtr() {
		if (NULL != _mysql_conn && NULL != _pool) release();
}
